﻿using DataHelper;
using JKYGL.Models;
using Microsoft.AspNetCore.Mvc;
using System.Diagnostics;
using System.IO.Compression;

namespace JKYGL.Controllers
{
    public class HomeController : Controller
    {
        private readonly ILogger<HomeController> _logger;

        public HomeController(ILogger<HomeController> logger)
        {
            _logger = logger;
        }
        public IActionResult BAKUP()
        {
            //备份数据库
            //备份照片
            string bakfilenameid = Guid.NewGuid().ToString();
            string sql = $@"BACKUP DATABASE ZhangFen TO DISK = 'd:\bak\JKY\JKY{bakfilenameid}.BAK' WITH FORMAT,CHECKSUM ";
            SqlHelper.ExecuteNonQueryBySQL(sql);
           
            string filePath = $@"D:\bak\JKY\JLY{bakfilenameid}.zip";
            CompressFileZip($@"d:\bak\JKY\JKY{bakfilenameid}.BAK",filePath);
            return File(new FileStream(filePath, FileMode.Open), "application/x-zip-compressed");
          
        }
        public IActionResult Index()
        {
            return View();
        }

        public IActionResult Privacy()
        {
            return View();
        }

        [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
        public IActionResult Error()
        {
            return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier });
        }
        public static void CompressFileZip(string filePath, string zipPath)
        {

            FileInfo fileInfo = new FileInfo(filePath);
            string dirPath = fileInfo.DirectoryName?.Replace("\\", "/") + "/";
            string tempPath = dirPath + Guid.NewGuid() + "_temp/";
            if (!Directory.Exists(tempPath))
            {
                Directory.CreateDirectory(tempPath);
            }
            fileInfo.CopyTo(tempPath + fileInfo.Name);
            try
            {
                if (System.IO.File.Exists(zipPath))
                    System.IO.File.Delete(zipPath);

                ZipFile.CreateFromDirectory(tempPath, zipPath);

            }
            catch
            { }
            DirectoryInfo directory = new(tempPath);
            if (directory.Exists)
            {
                //将文件夹属性设置为普通,如：只读文件夹设置为普通
                directory.Attributes = FileAttributes.Normal;

                directory.Delete(true);
            }
        }


    }
}